export * from "./Query";
import { strParse } from "./Query";

declare const wx: any, qq: any;

export class Mfs {
  public readonly set: (key: string, data: any) => void;
  public readonly get: (key: string) => any;
  public readonly del: (key: string) => void;
  private readonly key: () => string[];
  public get keys() { return this.key(); }

  constructor () {
    let isUni = false;
    try { isUni = !!uni; } catch (_) { }
    if (isUni) {
      if (uni.getFileSystemManager as any) {
        const fs = uni.getFileSystemManager();
        let path = "./";
        // #ifdef MP-WEIXIN
        try { path = wx.env.USER_DATA_PATH; } catch (_) { }
        // #endif
        // #ifdef MP-QQ
        try { path = qq.env.USER_DATA_PATH; } catch (_) { }
        // #endif
        // #ifdef MP-TOUTIAO
        path = "ttfile://user";
        // #endif
        this.set = (key, data) => {
          try {
            fs.writeFileSync(`${path}/_f_${key}.json`, JSON.stringify(data), "utf8");
          } catch (_) { }
        };
        this.get = (key) => {
          try {
            return JSON.parse(fs.readFileSync(`${path}/_f_${key}.json`, "utf8") as string);
          } catch (_) { }
        };
        this.del = (key) => {
          console.log("删除", key);
          try {
            fs.unlinkSync(`${path}/_f_${key}.json`);
          } catch (_) { }
        };
        this.key = () => {
          const ret: string[] = [];
          fs.readdirSync(`${path}/`).forEach(n => {
            if (/^_f_\w+\.json$/.test(n)) {
              ret.push(n.substring(3, n.length - 5));
            }
          });
          return ret;
        };
      } else {
        this.set = uni.setStorageSync;
        this.get = (key) => {
          if (uni.getStorageInfoSync().keys.includes(key)) {
            return uni.getStorageSync(key);
          }
        };
        this.del = (key) => {
          uni.removeStorageSync(key);
        };
        this.key = () => uni.getStorageInfoSync().keys;
      }
    } else {
      this.set = (key, data) => { localStorage.setItem(key, JSON.stringify(data)); };
      this.get = (key) => strParse(localStorage.getItem(key));
      this.del = (key) => {
        localStorage.removeItem(key);
      };
      this.key = () => {
        const ret: string[] = [];
        for (let i = 0; i < localStorage.length; i++) {
          ret.push(localStorage.key(i) as string);
        }
        return ret;
      };
    }

  }
}